//
//  MHLoginViewModel.m
//  MiaoCircle
//
//  Created by acgera on 2018/4/10.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHLoginViewModel.h"
#import "MHNetworking.h"
#import "MHWeChatAccessToken.h"
#import "MHHTTPService+Login.h"
@interface MHLoginViewModel()
@property (nonatomic, readwrite, strong) RACCommand *weChatLoginCommand;
@property (nonatomic, readwrite, strong) RACCommand *argeeProtoclCommand;
@property (nonatomic, readwrite, strong) RACCommand *requestRemoteDataCommand;


@end


@implementation MHLoginViewModel
- (void)initialize
{
    [super initialize];
    self.prefersNavigationBarHidden = YES;
    @weakify(self);
    
    
    self.accountLoginCommand =  [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        
            self.requestRemoteDataCommand =  [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
                @strongify(self);
                
                void (^doNext)(MHUser *) = ^(MHUser *user){
                    @strongify(self);
                    /// 存储登录账号
                    //                [SAMKeychain setRawLogin:self.phone];
                    IMALoginParam *loginParam =  [IMALoginParam new];
                    BOOL isAutoLogin = [IMAPlatform isAutoLogin];
                    if (isAutoLogin)
                    {
                        loginParam = [IMALoginParam loadFromLocal];
                    }
                    else
                    {
                        loginParam = [[IMALoginParam alloc] init];
                    }
                    
                    [IMAPlatform configWith:loginParam.config];
                    loginParam.identifier = [NSString stringWithFormat:@"%d",user.userId];
                    loginParam.userSig = user.usersig;
                    loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
                    [[HUDHelper sharedInstance] syncLoading:@"正在登录"];
                    [[IMAPlatform sharedInstance] login:loginParam succ:^{
                        [[HUDHelper sharedInstance] syncStopLoadingMessage:@"登录成功"];
                        /// 存储用户数据
                        [[self.services client] loginUser:user];
                        [loginParam saveToLocal];
                       
                        /// 切换更控制器
                        dispatch_async(dispatch_get_main_queue(), ^{
                            /// 发通知
                            [[NSNotificationCenter defaultCenter] postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey:@(MHSwitchRootViewControllerFromTypeLogin)}];
                        });
                        
                    } fail:^(int code, NSString *msg) {
                        [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, msg) delay:2 completion:^{
                            //                        [weakSelf pullLoginUI];
                        }];
                    }];
                };
                
                return  [[[self.services.client loginByWithAccout:self.account password:self.password] mh_parsedResults] doNext:doNext];
                
                
            }];
            
            [self.requestRemoteDataCommand execute:nil];
//        }else
//        {
//
//            [OpenShare WeixinAuth:@"snsapi_userinfo" Success:^(NSDictionary *message) {
//                @strongify(self);
//                [self getWebChatAccessTokenWithCode:message[@"code"]];
//            } Fail:^(NSDictionary *message, NSError *error) {
//
//            }];
//
//        }
        
        return [RACSignal empty];
    }];
    self.weChatLoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
         [[HUDHelper sharedInstance] syncLoading:@"正在登录"];
//        if(![AXAppDelegate sharedDelegate].passAudit)
//        {
//            self.requestRemoteDataCommand =  [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//                @strongify(self);
//
//                void (^doNext)(MHUser *) = ^(MHUser *user){
//                    @strongify(self);
//                    /// 存储登录账号
//                    //                [SAMKeychain setRawLogin:self.phone];
//                    IMALoginParam *loginParam =  [IMALoginParam new];
//                    BOOL isAutoLogin = [IMAPlatform isAutoLogin];
//                    if (isAutoLogin)
//                    {
//                        loginParam = [IMALoginParam loadFromLocal];
//                    }
//                    else
//                    {
//                        loginParam = [[IMALoginParam alloc] init];
//                    }
//
//                    [IMAPlatform configWith:loginParam.config];
//                    loginParam.identifier = [NSString stringWithFormat:@"%d",user.userId];
//                    loginParam.userSig = user.usersig;
//                    loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
//                    [[HUDHelper sharedInstance] syncLoading:@"正在登录"];
//                    [[IMAPlatform sharedInstance] login:loginParam succ:^{
//                        [[HUDHelper sharedInstance] syncStopLoadingMessage:@"登录成功"];
//                        /// 存储用户数据
//                        [[self.services client] loginUser:user];
//                        [loginParam saveToLocal];
//                        /// 切换更控制器
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            /// 发通知
//                            [[NSNotificationCenter defaultCenter] postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey:@(MHSwitchRootViewControllerFromTypeLogin)}];
//                        });
//
//                    } fail:^(int code, NSString *msg) {
//                        [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, msg) delay:2 completion:^{
//                            //                        [weakSelf pullLoginUI];
//                        }];
//                    }];
//                };
//
//                return  [[[self.services.client loginByAccout] mh_parsedResults] doNext:doNext];
//
//
//            }];
//
//            [self.requestRemoteDataCommand execute:nil];
//        }else
//        {
        
            [OpenShare WeixinAuth:@"snsapi_userinfo" Success:^(NSDictionary *message) {
                @strongify(self);
                [self getWebChatAccessTokenWithCode:message[@"code"]];
            } Fail:^(NSDictionary *message, NSError *error) {
                
            }];
            
//        }
        
        return [RACSignal empty];
    }];
}


-(void) getWebChatAccessTokenWithCode:(NSString *)code {
    NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",MHWECHATAPPID,MHWECHATSECRET,code];
    [MHNetworking postWithTcUrlString:urlString paramter:nil success:^(NSString *jsonStr, NSDictionary *jsonDic) {
        NSLog(@"%@",jsonDic);
        [self getUserInfoWithAccessToken:[jsonDic objectForKey:@"access_token"] andOpenId:[jsonDic objectForKey:@"openid"]];
    } failure:^(NSError *error) {
        [[HUDHelper sharedInstance] syncStopLoadingMessage:@"登录失败"];
    }];
}

- (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId{

    NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    [MHNetworking postWithTcUrlString:urlString paramter:nil success:^(NSString *jsonStr, NSDictionary *jsonDic) {
        NSLog(@"%@",jsonDic);
        MHWeChatAccessToken *wechatToken = [MHWeChatAccessToken yy_modelWithJSON:jsonStr];
        @weakify(self);
        self.requestRemoteDataCommand =  [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
             @strongify(self);
            
            void (^doNext)(MHUser *) = ^(MHUser *user){
                @strongify(self);
                /// 存储登录账号
//                [SAMKeychain setRawLogin:self.phone];
                IMALoginParam *loginParam =  [IMALoginParam new];
                BOOL isAutoLogin = [IMAPlatform isAutoLogin];
                if (isAutoLogin)
                {
                    loginParam = [IMALoginParam loadFromLocal];
                }
                else
                {
                    loginParam = [[IMALoginParam alloc] init];
                }
                [IMAPlatform configWith:loginParam.config];
                
                loginParam.identifier = [NSString stringWithFormat:@"%d",user.userId];
                loginParam.userSig = user.usersig;
                loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
               
                [[IMAPlatform sharedInstance] login:loginParam succ:^{
                    [[HUDHelper sharedInstance] syncStopLoadingMessage:@"登录成功"];
                    /// 存储用户数据
                    [[self.services client] loginUser:user];
                    [loginParam saveToLocal];
                    
                    /// 切换更控制器
                    [[IMAPlatform sharedInstance] configOnLoginSucc:loginParam];
                    [[AXAppDelegate sharedDelegate] registNotification];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        /// 发通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey:@(MHSwitchRootViewControllerFromTypeLogin)}];
                    });
             
                } fail:^(int code, NSString *msg) {
                    [[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, msg) delay:2 completion:^{
//                        [weakSelf pullLoginUI];
                    }];
                }];
                
               
            };
            
                return  [[[self.services.client thirdPartLoginWithPlatform:MHUserLoginChannelTypeWeChatId appId:MHWECHATAPPID openId:wechatToken.openid unionId:wechatToken.unionid token:accessToken nickName:wechatToken.nickname headImagUrl:wechatToken.headimgurl] mh_parsedResults] doNext:doNext];
            
            
        }];
        
        [self.requestRemoteDataCommand execute:nil];
       
        
        
        
        
        
    } failure:^(NSError *error) {
        nil;
    }];
}
@end
